package com.qs.sckill.exception;

import com.qs.sckill.result.CodeMsg;
import com.qs.sckill.result.Result;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * 自定义全局异常处理器
 *
 * @author qinyupeng
 * @since 2019-07-19 16:56:51
 */
@ControllerAdvice
@ResponseBody
public class GlobalExceptionHandler {

    @ExceptionHandler(value = Exception.class)
    public Result<String> exceptionHandler(HttpServletRequest request, Exception e) {
        e.printStackTrace();
        //如果抛出的是自定义全局异常
        if (e instanceof GlobalException) {
            GlobalException ex = (GlobalException) e;
            return Result.error(ex.getCodeMsg());
        } else if (e instanceof BindException) {
            //如果是参数绑定异常（参数校验不通过）
            BindException ex = (BindException) e;
            List<ObjectError> errors = ex.getAllErrors();
            if (CollectionUtils.isEmpty(errors)) {
                return Result.error(CodeMsg.SERVER_ERROR);
            }

            ObjectError error = errors.get(0);
            String errMsg = error.getDefaultMessage();
            //返回参数校验不通过信息
            return Result.error(CodeMsg.BIND_ERROR.fillArgs(errMsg));
        } else {
            return Result.error(CodeMsg.SERVER_ERROR);
        }
    }

}
